package com.hebang.stcommunityapp;

import android.content.Context;

import org.apache.http.conn.ssl.AllowAllHostnameVerifier;

import java.util.concurrent.TimeUnit;

import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class NetClient {
    private static final int CONNECT_TIMEOUT = 5* 1000;
    private static final int READ_TIME_OUT = 10 * 1000;
    private static final int WRITE_TIME_OUT = 10 * 1000;

    private OkHttpClient.Builder builder;
    private static NetClient instance;
    private Context mCtx;
    private NetClient(Context ctx) {
        this.mCtx = ctx;
        builder = new OkHttpClient.Builder()
                .connectTimeout(CONNECT_TIMEOUT, TimeUnit.MILLISECONDS)
                .readTimeout(READ_TIME_OUT, TimeUnit.MILLISECONDS)
                .writeTimeout(WRITE_TIME_OUT, TimeUnit.MILLISECONDS)
                .hostnameVerifier(new AllowAllHostnameVerifier());
        ;
        builder.build();
    }

    public static NetClient getInstance(Context ctx) {
        if (instance == null) {
            instance = new NetClient(ctx);
        }
        return instance;
    }

    public void postAsynWithStringParam(String url, String param , Callback callback) {
        try {
            Request request = new Request.Builder()
                    .url(url+param)//.header("keyword","SxSh")
                    .build();
            builder.build().newCall(request).enqueue(callback);
            return;

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void postAsynWithJson(String url, String param, String token, Callback callback) {
        try {
            RequestBody formBody = new FormBody.Builder()
                    .add("params", param)
                    .build();
            if (token != null) {
                Request request = new Request.Builder()
                        .addHeader("token", token)
                        .url(url)//.header("keyword","SxSh")
                        .post(formBody)
                        .build();
                builder.build().newCall(request).enqueue(callback);
            } else {
                Request request = new Request.Builder()
                        .url(url)//.header("keyword","SxSh")
                        .post(formBody)
                        .build();
                builder.build().newCall(request).enqueue(callback);
            }
            return;

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
